from grid_env_ideal_obs_repeat_task import *
from grid_agent import *
from checkpoint_utils import *
from maze_factory import *
from replay_config import *
import argparse
import json
import sys
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from sklearn.manifold import TSNE
import random
from sklearn.decomposition import PCA
from matplotlib.animation import FuncAnimation
from sklearn.cluster import KMeans
import threading
from matplotlib.ticker import FuncFormatter
import mplcursors

# analysis of phase space

def progress_bar(current, total, barLength = 100):
    percent = float(current) * 100 / total
    arrow = '-' * int(percent/100 * barLength - 1) + '>'
    spaces = ' ' * (barLength - len(arrow))

    print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')
    sys.stdout.flush()

@partial(jax.jit, static_argnums=(3,))
def model_forward(variables, state, x, model):
    """ forward pass of the model
    """
    return model.apply(variables, state, x)

@jit
def get_action(y):
    return jnp.argmax(y)
get_action_vmap = jax.vmap(get_action)

# load landscape and states from file
def load_task(pth = "./logs/task.json", display = True):
    # open json file
    with open(pth, "r") as f:
        data = json.load(f)
        landscape = data["data"]
        state = data["state"]
        goal = data["goal"]
        if display:
            print("state: ", state)
            print("goal: ", goal)
            print("landscape: ", landscape)
    return landscape, state, goal

# 全局变量，用于存储和图像显示线程交互的数据
class imgview:
    global_image = None
    imgview_exit = False
    trajectory = []
    focus_i = 0
    traj_i = 0

imgview_data = imgview()

# 定义一个函数，用于在独立线程中显示图像
def show_image():
    grid_size_display = 20
    while not imgview_data.imgview_exit:
        # 检查全局变量是否有图像
        if imgview_data.global_image is not None:
            img = np.copy(imgview_data.global_image)
            state_x = imgview_data.trajectory[imgview_data.traj_i][0]
            state_y = imgview_data.trajectory[imgview_data.traj_i][1]
            cv2.circle(img, (state_y * grid_size_display + int(grid_size_display/2), state_x * grid_size_display + int(grid_size_display/2)), 7, (0, 0, 255), -1, cv2.LINE_AA)
            # 显示图像
            cv2.imshow("Image", img)
            key = cv2.waitKey(1)
            if key == ord('a'):
                imgview_data.focus_i -= 1
                print("imgview_data.focus_i: ", imgview_data.focus_i)
            elif key == ord('d'):
                imgview_data.focus_i += 1
                print("imgview_data.focus_i: ", imgview_data.focus_i)
        else:
            # 图像还未产生，等待100毫秒
            time.sleep(0.1)

# 计算雅克比矩阵
@jax.jit
def rnn_run(x, mat_intr, bias1):
    intr_vector = jnp.dot(x, mat_intr) + bias1
    intr_vector = jnp.tanh(intr_vector)
    return intr_vector
jacobian_fun = jax.jacrev(rnn_run)
jacobian_vmap = jax.jit(jax.vmap(jacobian_fun, in_axes=(0,None,None)))

@jax.jit
def vector_field_LDS(x, jacobian):
    vector = jnp.dot(jacobian, x)
    return vector
vector_field_LDS_vmap = jax.jit(jax.vmap(vector_field_LDS, in_axes=(0,0)))

# run linear dynamical system using vector_field_LDS_vmap
def run_LDS(X0, t, dt, jacobian, mat_intr, bias1):

    pass

def ivf():

    """ parse arguments
    """
    rpl_config = ReplayConfig()

    parser = argparse.ArgumentParser()
    parser.add_argument("--model_pth", type=str, default=rpl_config.model_pth)
    parser.add_argument("--map_size", type=int, default=rpl_config.map_size)
    parser.add_argument("--task_pth", type=str, default=rpl_config.task_pth)
    parser.add_argument("--log_pth", type=str, default=rpl_config.log_pth)
    parser.add_argument("--nn_size", type=int, default=rpl_config.nn_size)
    parser.add_argument("--nn_type", type=str, default=rpl_config.nn_type)
    parser.add_argument("--show_kf", type=str, default=rpl_config.show_kf)
    parser.add_argument("--visualization", type=str, default=rpl_config.visualization)
    parser.add_argument("--video_output", type=str, default=rpl_config.video_output)
    parser.add_argument("--life_duration", type=int, default=rpl_config.life_duration)
    parser.add_argument("--start_i", type=int, default=rpl_config.start_i)
    parser.add_argument("--end_i", type=int, default=rpl_config.end_i)
    parser.add_argument("--load_data", type=int, default=rpl_config.load_data)

    args = parser.parse_args()

    rpl_config.model_pth = args.model_pth
    rpl_config.map_size = args.map_size
    rpl_config.task_pth = args.task_pth
    rpl_config.log_pth = args.log_pth
    rpl_config.nn_size = args.nn_size
    rpl_config.nn_type = args.nn_type
    rpl_config.show_kf = args.show_kf
    rpl_config.visualization = args.visualization
    rpl_config.video_output = args.video_output
    rpl_config.life_duration = args.life_duration
    rpl_config.start_i = args.start_i
    rpl_config.end_i = args.end_i
    rpl_config.load_data = args.load_data

    if rpl_config.load_data == 0:

        """ load model
        """
        params = load_weights(rpl_config.model_pth)
        # 定义一个函数，用于生成随机权重
        def init_weights_r(key, shape):
            return jax.random.normal(key, shape)
        # 生成一个随机的 PRNGKey
        key = jax.random.PRNGKey(np.random.randint(0, 1000))
        # key = jax.random.PRNGKey(4512)
        # 使用 tree_map 遍历 params 对象，并使用 init_weights 函数生成随机权重
        random_params = jax.tree_map(lambda x: init_weights_r(key, x.shape), params)
        # params = random_params

        # get elements of params
        tree_leaves = jax.tree_util.tree_leaves(params)
        for i in range(len(tree_leaves)):
            print("shape of leaf ", i, ": ", tree_leaves[i].shape)

        bias1 = jnp.array(tree_leaves[0])
        mat1 = jnp.array(tree_leaves[1])
        print("mat1.shape: ", mat1.shape)
        print("bias1: ", bias1)

        mat_obs = jnp.array(tree_leaves[1])[rpl_config.nn_size:rpl_config.nn_size+10,:]
        mat_intr = jnp.array(tree_leaves[1])[0:rpl_config.nn_size,:]
        print("mat_obs.shape: ", mat_obs.shape)
        
        """ create agent
        """
        if rpl_config.nn_type == "vanilla":
            model = RNN(hidden_dims = rpl_config.nn_size)
        elif rpl_config.nn_type == "gru":
            model = GRU(hidden_dims = rpl_config.nn_size)

        # check if param fits the agent
        if rpl_config.nn_type == "vanilla":
            assert params["params"]["Dense_0"]["kernel"].shape[0] == rpl_config.nn_size + 10

        n_samples = 10000
        k1 = npr.randint(0, 1000000)
        rnn_state = model.initial_state_rnd(n_samples, k1)
        rnn_state_old = rnn_state.copy()
        diff = jnp.abs(rnn_state - rnn_state_old)
        rnn_state_old = rnn_state.copy()
        diff_norm = jnp.linalg.norm(diff, axis=1)
        diff_norm_old = diff_norm.copy()
        norm_std = diff_norm.copy()

        rnn_state_init = rnn_state.copy()

        obs_zero = jnp.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(n_samples)])

        rnn_state_trajectory = []
        intr_field = []

        for t in range(rpl_config.life_duration):

            progress_bar(t, rpl_config.life_duration)

            intr_vector = np.dot(rnn_state, mat_intr) + bias1
            intr_vector = np.tanh(intr_vector)
            intr_field.append(intr_vector - rnn_state)

            rnn_state_trajectory.append(np.array(rnn_state).copy())
            
            """ model forward 
            """
            # rnn_state, y1 = model_forward(params, rnn_state, obs_zero, model)
            rnn_state = intr_vector
            
        print(rnn_state.shape)
        print(norm_std.shape)
        rnn_state_np = np.array(rnn_state)

        # 将 rnn_state_trajectory 展开成 rnn_state_np 的形状
        rnn_state_trajectory_np = np.array(rnn_state_trajectory)
        rnn_state_trajectory_np = rnn_state_trajectory_np.reshape(-1, rnn_state_trajectory_np.shape[-1])
        print("shape of rnn_state_trajectory_np: ", rnn_state_trajectory_np.shape)

        # 将 intr_field 展开成 rnn_state_np 的形状
        intr_field_np = np.array(intr_field)
        intr_field_np = intr_field_np.reshape(-1, intr_field_np.shape[-1])
        print("shape of intr_field_np: ", intr_field_np.shape)

        # # 对 rnn_state_np 进行 PCA
        # intrinsic_pca = PCA()
        # # pca.fit(rnn_state_np)
        # intrinsic_pca.fit(rnn_state_trajectory_np)

        # # # 打印 variance ratio
        # # print(pca.explained_variance_ratio_)

        # rnn_state_trajectory_np_pca = intrinsic_pca.transform(rnn_state_trajectory_np)

        # 计算雅克比矩阵

        # 随机化 sample_id
        sample_id = np.random.randint(0, rnn_state_trajectory_np.shape[0])
        # sample_id = 15
        sample_position = rnn_state_trajectory_np[sample_id].copy() #rnn_run(rnn_state_trajectory_np[sample_id], mat_intr, bias1)
        jacobian_of_x = jacobian_fun(jnp.array(sample_position), mat_intr, bias1)
        print("shape of jacobian_of_x: ", jacobian_of_x.shape)
        print("sample_id ============ ",sample_id)

        # 验证一阶泰勒展开和原始向量场的差异
        # 生成一个距离 rnn_state_trajectory_np[sample_id] 很小的随机微小扰动后的位置
        sample_adjacent = sample_position + np.random.uniform(0, 0.15, sample_position.shape)
        # 计算向量场在这个位置的值
        sample_adjacent_next = rnn_run(sample_adjacent, mat_intr, bias1)
        sample_adjacent_next_est = rnn_run(sample_position, mat_intr, bias1) + np.dot(jacobian_of_x, sample_adjacent - sample_position)
        # 显示两个向量之间的差异模长
        print("norm of difference : ", np.linalg.norm(sample_adjacent_next - sample_adjacent_next_est))

        # 收敛验证
        sample_adjacent_next_est_old = sample_adjacent_next_est.copy()
        sample_adjacent_next_est = np.random.uniform(0, 0.15, sample_position.shape)
        for k in range(1000):
            sample_adjacent_next_est = rnn_run(sample_position, mat_intr, bias1) + np.dot(jacobian_of_x, sample_adjacent_next_est - sample_position)
            print("norm of iter : ", np.linalg.norm(sample_adjacent_next_est - sample_position))
            sample_adjacent_next_est_old = sample_adjacent_next_est.copy()
        
        # # 对 jacobian_of_x 线性系统单独进行迭代
        # sample_position_old = np.random.uniform(0, 0.15, sample_position.shape)
        # sample_position1 = sample_position_old.copy()
        # for k in range(1000):
        #     sample_position1_dot = np.dot(jacobian_of_x, sample_position1)
        #     sample_position1 = sample_position1 + sample_position1_dot*0.01
        #     print("norm of iter : ", np.linalg.norm(sample_position1 - sample_position_old))
        #     sample_position_old = sample_position1.copy()
        
        # # 计算 jacobian_of_x 的所有特征值
        # eigenvalues = np.linalg.eigvals(jacobian_of_x)
        # # 对 eigenvalues 按照实部从大到小进行排序
        # eigenvalues = np.sort(eigenvalues)[::-1]
        # print("sorted eigenvalues of jacobian_of_x: ", eigenvalues)

        # # 判断 eigenvalues 中是否含有实部大于零的元素
        # if any(np.real(eigenvalues) > 0.1):
        #     print("存在实部大于零的项")
        # else:
        #     print("不存在实部大于零的项")
        

        # # 计算 jacobian_of_x 的所有特征向量
        # eigenvectors = np.linalg.eig(jacobian_of_x)[1]

        # # 输出结果
        # print("shape of eigenvectors: ", eigenvectors.shape)
        # print(eigenvectors[0])

        # # 将 jacobian_of_x 用热度图显示
        # fig, ax = plt.subplots()
        # im = ax.imshow(jacobian_of_x, cmap='hot', interpolation='nearest')
        # # 显示颜色条
        # cbar = ax.figure.colorbar(im, ax=ax)
        # plt.show()

        # # 将 jacobian_of_x 绘制成三维曲面
        # fig = plt.figure()
        # ax = fig.add_subplot(111, projection='3d')
        # x = np.arange(0, rpl_config.nn_size, 1)
        # y = np.arange(0, rpl_config.nn_size, 1)
        # X, Y = np.meshgrid(x, y)
        # Z = jacobian_of_x
        # ax.plot_surface(X, Y, Z, cmap='hot')
        # plt.show()

        # batch_jac = jacobian_vmap(jnp.array(rnn_state_trajectory_np))
        # print("shape of batch_jac: ", batch_jac.shape)

    # 使用 jacobian_of_x 进行动力学模拟、pca分析、绘制相空间轨迹、绘制向量场


if __name__ == "__main__":
    
    ivf()